<?php

namespace app\admin\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\Model;

class Staff extends Model
{



    protected $autoWriteTimestamp='datetime';
    public function getStatusAttr($value)
    {
        $Status = [1=>'显示',0=>'隐藏'];
        return $Status[$value];
    }



    public function getStoreInfo(){

     return   $this->hasOne(Role::class,'id','role_id')->bind(['role_name'=>'name','store_id']);
    }



    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public  static function getList(){

        $where=[];

        $store_json=session('store_id');
        $wheres[]=['store_id','in',$store_json];
        return  self::with(['getStoreInfo'=>function($query)use($wheres){
            $query->where($wheres);
        }])->where($where)->page(input('page',1))->limit(input('limit',20))->select()->append(['store_name']);

    }
    public static function insertStaff($add){
        try {

                $result=self::create($add);
                if($result){
                    $data = array(
                        'code' => 200,
                        'msg' => '成功!',
                        'url'=>url('/Department/getList')->build()
                    );
                    return $data;
                }else{
                    $data = array(
                        'code' => 40002,
                        'msg' => '失败!',
                    );
                    return $data;
                }
                // dump($result);die;

        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $e->getError();
        }

    }

    public static function modifyStaff($add){
        try {
                $result=self::where(['id'=>input('id')])->save($add);

                if(!empty($result)){
                    $data = array(
                        'code' => 200,
                        'msg' => '成功!',
                        'url'=>url('/Department/getList')->build()
                    );

                    return $data;
                }else{
                    $data = array(
                        'code' => 40002,
                        'msg' => '成功!',
                    );
                    return $data;
                }

        } catch (ValidateException $e) {
            // 验证失败 输出错误信息

            return $e->getError();
        }

    }

}